<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-position="labelPosition"
           :class="isEdit?'':'formItem'">
    <!--年检信息-->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">年检信息</span>
      </div>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="本次年检时间:" prop="inspectionTime">
            <el-date-picker type="date" placeholder="选择本次年检时间" v-if="isEdit" value-format='yyyy-MM-dd'
                            @change="handleDate" :clearable="false"
                            style="width: 100%;" v-model="ruleForm.inspectionTime">
            </el-date-picker>
            <span v-else>{{ ruleForm.inspectionTime }}</span>
          </el-form-item>

        </el-col>
        <el-col :span="8">
          <el-form-item label="本次年检线上/线下:" prop="onlineOffline">
            <el-select v-model="ruleForm.onlineOffline"
                       placeholder="选择本次年检线上/线下" style="width: 100%;"
                       v-if="isEdit">
              <el-option label="线上" value="1">
              </el-option>
              <el-option label="线下" value="2">
              </el-option>
            </el-select>
            <span v-else>{{ selectDictLabel(dict.type.online_offline, ruleForm.onlineOffline) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计下次年检到期日:" prop="inspectionNextTime">
            <el-date-picker type="date" placeholder="选择预计下次年检到期日" v-if="isEdit" value-format='yyyy-MM-dd'
                            :clearable="false"
                            style="width: 100%;" v-model="ruleForm.inspectionNextTime">
            </el-date-picker>
            <span v-else>{{ ruleForm.inspectionNextTime }}</span>
          </el-form-item>

        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="预计下次年检线上/线下:" prop="expireOnlineOffline">
            <el-select v-model="ruleForm.expireOnlineOffline" placeholder="选择预计下次年检线上/线下"
                       style="width: 100%;"
                       v-if="isEdit">
              <el-option label="线上" value="1">
              </el-option>
              <el-option label="线下" value="2">
              </el-option>

            </el-select>
            <span v-else>{{
                selectDictLabel(dict.type.online_offline,
                    ruleForm.expireOnlineOffline)
              }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年检费:" prop="inspectionPrice">
            <el-input v-if="isEdit" v-model="ruleForm.inspectionPrice" placeholder="输入年检费"
            v-thousand
            @change="changeAmount('inspectionPrice')"></el-input>
            <span v-else>{{ format_thousand(ruleForm.inspectionPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年检代办费:" prop="inspectionAgentPrice">
            <el-input v-if="isEdit" v-model="ruleForm.inspectionAgentPrice" placeholder="输入年检代办费"
            v-thousand
            @change="changeAmount('inspectionAgentPrice')"></el-input>
            <span v-else>{{ format_thousand(ruleForm.inspectionAgentPrice) }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="综合检测费:" prop="comprehensivePrice">
            <el-input v-if="isEdit" v-model="ruleForm.comprehensivePrice" placeholder="输入综合检测费"
            v-thousand
            @change="changeAmount('comprehensivePrice')"></el-input>
            <span v-else>{{ format_thousand(ruleForm.comprehensivePrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="二维费用:" prop="twoDimensionPrice">
            <el-input v-if="isEdit" v-model="ruleForm.twoDimensionPrice" placeholder="输入二维费用"
            v-thousand
            @change="changeAmount('twoDimensionPrice')"></el-input>
            <span v-else>{{ format_thousand(ruleForm.twoDimensionPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他费用:" prop="otherPrice">
            <el-input v-if="isEdit" v-model="ruleForm.otherPrice" placeholder="输入其他费用"
            v-thousand
            @change="changeAmount('otherPrice')"></el-input>
            <span v-else>{{ format_thousand(ruleForm.otherPrice) }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="年检总金额:">
            <el-input v-if="isEdit" 
            v-thousand
            v-model="ruleForm.inspectionAllPrice" placeholder="输入年检总金额"
                      disabled></el-input>
            <span v-else>{{ format_thousand(ruleForm.inspectionAllPrice) }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="年检标识:" prop="inspectionIdenUrl" class="formitem">
            <image-common v-model="ruleForm.inspectionIdenUrl" :disabled="!isEdit" :limit="20"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" :class="isEdit ? '' : 'elRow'">
          <el-form-item label="年检发票:" prop="inspectionInvoiceUrl" class="formitem">
            <image-common v-model="ruleForm.inspectionInvoiceUrl" :disabled="!isEdit" :limit="20"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24" :class="isEdit ? '' : 'elRow'">
        <el-col>
          <el-form-item label="附件:" class="formitem">
            <image-common v-model="ruleForm.attachmentUrl" :limit="20" :disabled="!isEdit" :upType="2"/>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="年检备注:">
            <el-input v-if="isEdit" placeholder="请输入年检备注" type="textarea" :rows="4"
                      v-model="ruleForm.remark"></el-input>
            <span v-else>{{ ruleForm.remark }}</span>
          </el-form-item>
        </el-col>

      </el-row>
    </el-card>

  </el-form>
</template>

<script>
import {effectDate} from "@/utils/libs/effectDate.js"
import {calculateLastInspectionDate} from "@/api/cwgd/cwgdApi.js";
import {A_formatTime} from "@/utils/utils.js"
export default {
  name: "processingAnnual",

  dicts: ["online_offline"],

  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },

  components: {
    LinkageSelect: () => import("../../../components/linkageSelect.vue"),
    ImgUpload: () => import("../../../components/ImgUpload"),
  },

  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "left";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
  },

  watch: {},

  data() {
    //年检标识效验
    var validateInspectionIdenUrl = (rule, value, callback) => {
      if (this.ruleForm.inspectionIdenUrl === "" || this.ruleForm.inspectionIdenUrl === null) {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };

    var validateInspectionInvoiceUrl = (rule, value, callback) => {
      if (this.value.inspectionInvoiceUrl === "" || this.ruleForm.inspectionInvoiceUrl === null) {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };

    var start = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
          that.ruleForm.inspectionTime,
          that.ruleForm.inspectionNextTime,
          '本次年检时间',
          '预计下次年检到期日'
      )
    };
    var end = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
          that.ruleForm.inspectionTime,
          that.ruleForm.inspectionNextTime,
          '本次年检时间',
          '预计下次年检到期日'
      )
    };

    //年检发效验
    return {
      isShow: true,
      isForm: true,
      method: {},
      routeQuery: {},
      inspectDetail: {},
      rules: {
        inspectionTime: [
          {
            required: this.state === "write",
            validator: start,
            trigger: "blur",
          },
        ],
        onlineOffline: [
          {
            required: this.state === "write",
            message: "请选择本次年检线上/线下",
            trigger: "blur",
          },
        ],
        inspectionNextTime: [
          {
            required: this.state === "write",
            type: "string",
            validator: end,
            trigger: "blur",
          },
        ],
        expireOnlineOffline: [
          {
            required: this.state === "write",
            message: "请选择预计下次年检线上/线下",
            trigger: "blur",
          },
        ],
        inspectionPrice: [
          {
            required: this.state === "write",
            message: "请输入年检费",
            trigger: "blur",
          },
        ],
        inspectionIdenUrl: [
          {
            required: this.state === "write",
            validator: validateInspectionIdenUrl,
            trigger: "blur",
          },
        ],
        inspectionInvoiceUrl: [
          {
            required: this.state === "write",
            validator: validateInspectionInvoiceUrl,
            trigger: "blur",
          },
        ],
        inspectionAgentPrice: [
          {
            required: this.state === "write",
            message: "请输入年检代办费",
            trigger: "blur",
          },
        ],
        comprehensivePrice: [
          {
            required: this.state === "write",
            message: "请输入综合检测费",
            trigger: "blur",
          },
        ],
        twoDimensionPrice: [
          {
            required: this.state === "write",
            message: "请输入二维费用",
            trigger: "blur",
          },
        ],
        otherPrice: [
          {
            required: this.state === "write",
            message: "请输入其他费用",
            trigger: "blur",
          },
        ],
      },
    };
  },

  created() {
  },
  mounted() {
  },
  methods: {
    //计算年检时间的
    handleDate(val) {
      this.ruleForm.inspectionTime = val
      let obj = {
        carId: this.ruleForm.carId,
        inspectionDate:this.ruleForm.inspectionTime
      }
      calculateLastInspectionDate(obj).then(res => {
        if(res.code === 200){
          this.ruleForm.inspectionNextTime = A_formatTime(res.data,'YYYY-MM-DD')|| ''
        }
      })
    },

    //年检总金额
    sumPrice() {
      let num = 0;
      num =
          Number(this.ruleForm.inspectionPrice) +
          Number(this.ruleForm.inspectionAgentPrice) +
          Number(this.ruleForm.comprehensivePrice) +
          Number(this.ruleForm.twoDimensionPrice) +
          Number(this.ruleForm.otherPrice);
      this.ruleForm.inspectionAllPrice = num
          .toString()
          .match(/^\d+(?:\.\d{0,2})?/)[0];
    },

    //效验
    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.ruleForm[str])) {
        this.ruleForm[str] = "";
      } else {
        let num = this.keepTwoDecimalPlaces(this.ruleForm[str])
        this.value[str] = num;

      }
      this.sumPrice();
    },

    keepTwoDecimalPlaces: function (num) {
      return num.toString().match(/^\d+(?:\.\d{0,2})?/)[0];
    },

    handleProcessingAnnual() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr();
            reject();
          }
        });
      });
    },
    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth",
        });
      });
    },

    //取消表单效验
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";
</style>


